package com.scen.upload.controller;

import com.scen.upload.domain.ActiverUser;
import com.scen.upload.utils.ZXingCodeEncodeUtils;
import com.scen.upload.vo.AjaxResult;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.filechooser.FileSystemView;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * ZXing二维码controller层
 *
 * @author Administrator
 * @title: ZxingController
 * @projectName upload
 * @description: TODO
 * @date 2021/7/3 0003
 */
@Log4j2
@RestController
@RequestMapping("system/zxing")
public class ZXingController {
    /**
     * 生成二维码并保存至电脑桌面
     *
     * @return
     */
    @PostMapping("createZXingCodeSaveToDisk")
    @ResponseBody
    public AjaxResult createZXingCodeSaveToDisk() throws IOException {
        String systemPath = String.valueOf(FileSystemView.getFileSystemView().getHomeDirectory().getAbsoluteFile());
        FileOutputStream fileOutputStream = new FileOutputStream(systemPath + "\\zxing.jpg");
        BufferedImage codeImage = ZXingCodeEncodeUtils.createZXingCodeNormal("http://yk.yunfeiyang.info:8090/YKKH/login.html", 400, 400);
        BufferedImage logoImage = ZXingCodeEncodeUtils.LogoMatrix(codeImage);
        boolean res = ImageIO.write(logoImage, "JPEG", fileOutputStream);
        fileOutputStream.flush();
        fileOutputStream.close();
        return AjaxResult.success("二维码已生成并成功保存至桌面", res);
    }

    /**
     * 生成二维码并返回图片
     * 将用户数据组装为json并返回
     *
     * @return
     */
    @GetMapping("createZXingCodeImage")
    @ResponseBody
    public AjaxResult createZXingCodeImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 用户数据组装为json
        Subject subject = SecurityUtils.getSubject();
        ActiverUser activerUser = (ActiverUser) subject.getPrincipal();
        String userName = activerUser.getUser().getUserName();
        Integer sexStatus = Integer.valueOf(activerUser.getUser().getSex());
        String sex = "";
        if (sexStatus == 1) {
            sex = "男";
        } else {
            sex = "女";
        }
        Integer age = activerUser.getUser().getAge();
        String json = "{\"name\":\"" + userName + "\",\"sex\":\"" + sex + "\",\"age\":" + age + "}";
        ServletOutputStream outputStream = response.getOutputStream();
        BufferedImage codeImage = ZXingCodeEncodeUtils.createZXingCodeNormal(json, 200, 200);
        BufferedImage logoImage = ZXingCodeEncodeUtils.LogoMatrix(codeImage);
        ImageIO.write(logoImage, "jpeg", outputStream);
        outputStream.flush();
        outputStream.close();
        return AjaxResult.success("二维码已生成");
    }
}
